import Vue from 'vue';
import iView from 'iview';
import Util from '../libs/util';
import VueRouter from 'vue-router';
import routers from './router';
import {authUser} from '../api/sys/user/user-api';

Vue.use(VueRouter);

// 路由配置
const RouterConfig = {
    //mode: 'history',
    routes: routers
};

export const router = new VueRouter(RouterConfig);

router.beforeEach((to, from, next) => {
    iView.LoadingBar.start();
    Util.title(to.meta.title);
    if(to.meta.requireAuth){
        // 将token传到后台判断当前的token是否有权限访问该地址
        authUser({token:localStorage.getItem('setToken') }).then(res => {
            if(res.result){
                next();
            }else{
                next({
                    path:'/login',
                    query:{redirect:to.fullPath}//登录成功以后跳转到该路由
                });
            }
        });
    }else{
        next();
    }
});

router.afterEach((to) => {
    iView.LoadingBar.finish();
    window.scrollTo(0, 0);
});